package cn.gjculture.shopping.api.export;

import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;


public abstract class ExportExcel <T>{

    protected Workbook wb = null;
    protected Sheet sheet = null;

    @Setter
    @Getter
    private List<String> titles = null;
    @Setter
    @Getter
    private String sheetName = "列表";
    @Setter
    @Getter
    private int[] position = {0, 0};

    @Getter
    @Setter
    private List<T>  datas=null;


    public void export(OutputStream os) throws IOException {
        init();
        addTitle();
        writeTitle();
        addData();
        if (wb != null) {
            wb.write(os);
            os.flush();
        }
    }

    private void writeTitle() {
        int x = getPosition()[0];
        int y = getPosition()[1];
        if (CollectionUtils.isEmpty(this.getTitles())) return;
        CellStyle style = this.wb.createCellStyle();
        Font font = this.wb.createFont();
        font.setFontHeightInPoints((short) 14);
        font.setBold(true);
        style.setFont(font);
        Row row = this.sheet.createRow(0 + y);
        for (int i = 0; i < this.getTitles().size(); i++) {
            Cell cell = row.createCell(i + x);
            cell.setCellValue(this.getTitles().get(i + x));
            cell.setCellStyle(style);
        }
        this.setPosition(new int[]{x, y + 1});

    }

    public abstract void addData();

    public void init() {
        wb = new XSSFWorkbook();
        sheet = wb.createSheet(this.sheetName);
    }

    public abstract void addTitle();


}
